import React, { PureComponent } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Table, InputNumber } from 'antd';
import styles from '@/utils/utils.less';

const FormItem = Form.Item;

class TableForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: props.detList || [],
      listIndex: 0,
      selectPdList: {},
      isDisable: false,
      sumPrice:
        props.detList.reduce((total, currentValue) => total + currentValue.fee || 0, 0) || 0,
    };
  }

  componentDidMount() {
    const { productList, detList } = this.props;
    if (!detList.length) {
      this.addList();
    } else {
      const newData = detList.map(item => ({ ...item, key: item.pdId }));
      this.setState({ data: newData, isDisable: newData.length === productList.length });
    }
  }

  // 添加数据
  addList = () => {
    const { productList } = this.props;
    const { data, listIndex } = this.state;
    const newData = data.map(item => ({ ...item }));
    newData.push({
      key: `pdId_${listIndex}`,
      pdId: undefined,
      fee: undefined,
    });
    this.state.listIndex += 1;
    this.setState({ data: newData });
    if (productList.length && productList.length === newData.length) {
      this.state.isDisable = true;
    }
  };

  // 删除数据
  delList = key => {
    const { data } = this.state;
    const newData = data.filter(item => item.key !== key);
    this.setState({ data: newData });
    const { productList } = this.props;
    const { selectPdList } = this.state;
    selectPdList[key] = '';
    const curSleArr = [];
    Object.keys(selectPdList).forEach(k => {
      curSleArr.push(selectPdList[k]);
    });

    const showArr = [];
    productList.forEach(item => {
      if (curSleArr.indexOf(item.pdId) === -1) {
        showArr.push(item);
      }
    });
    if (productList.length && productList.length > newData.length) {
      this.setState({ isDisable: false });
    }
    this.setState({ selectPdList });
  };

  // 更改数据
  changeData = (value, key, target) => {
    const { productList } = this.props;
    const { selectPdList, data } = this.state;
    if (String(target) === 'pdId') {
      selectPdList[key] = value;
      const curSleArr = [];
      Object.keys(selectPdList).forEach(k => {
        curSleArr.push(selectPdList[k]);
      });

      const showArr = [];
      productList.forEach(item => {
        if (curSleArr.indexOf(item.pdId) === -1) {
          showArr.push(item);
        }
      });
      this.setState({ selectPdList });
    }
    if (String(target) === 'fee') {
      // 计算总价
      const newData = data;
      newData.forEach(item => {
        const temp = item;
        if (String(item.key) === String(key)) {
          temp[target] = value;
        }
      });
      const sumPrice = newData.reduce((total, currentValue) => total + currentValue.fee || 0, 0);
      this.setState({ sumPrice });
    }
    // let newData = this.state.data;
    // newData.map(item => {
    //   if (item.key == key) {
    //     item[target] = value
    //   }
    // })
  };

  //
  render() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { sumPrice, data } = this.state;
    const columns = [
      {
        title: '产品',
        dataIndex: 'pdId',
        width: '40%',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record, index) => (
          <FormItem style={{ margin: 0 }} className={styles.errorMsgRight}>
            {getFieldDecorator(`detList[${index}]['pdId']`, {
              rules: [
                {
                  required: true,
                  message: '请选择',
                },
              ],
              initialValue: record.pdId,
            })(<p />)}
          </FormItem>
        ),
      },
      {
        title: (
          <span>
            价格<span>(总价：{sumPrice})</span>
          </span>
        ),
        dataIndex: 'fee',
        align: 'right',
        width: '40%',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record, index) => (
          <FormItem style={{ margin: 0 }} className={styles.errorMsgRight}>
            {getFieldDecorator(`detList[${index}]['fee']`, {
              rules: [
                {
                  required: true,
                  message: '请输入',
                },
              ],
              initialValue: record.fee && parseInt(record.fee, 10),
            })(
              <InputNumber
                placeholder="请输入"
                min={1}
                max={9999999.99}
                style={{ width: 150 }}
                onChange={value => this.changeData(value, record.key, 'fee')}
              />
            )}
          </FormItem>
        ),
      },
    ];

    return (
      <div style={{ width: 500, margin: '0 auto' }}>
        <Table
          style={{ width: '100%' }}
          // loading={loading}
          columns={columns}
          dataSource={data}
          pagination={false}
          notFoundContent="暂无数据"
          rowKey={record => record.pdId || record.key}
          className={styles.errorMsg}
        />
      </div>
    );
  }
}

export default TableForm;
